import { rootValue, unitPrecision } from "@/config/const_var";
export const pxChangeRem = (px: number | string) => {
  px = parseFloat(px as string);
  const value =
    Math.round((px / rootValue) * 10 ** unitPrecision) / 10 ** unitPrecision;
  return value + "rem";
};
export const debounce = (fn: Function, delay: number = 300) => {
  let timer: any = null;
  return function (...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(fn.bind(null, ...args), delay);
  };
};
export const chunkArray = (array: any[], size: number) => {
  let result = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
};
export const getImg = (str: string) => {
  return new URL(`../assets/img/${str}`, import.meta.url).href;
};
export const getIcon = (str: any) => {
  return new URL(`../assets/icons/${str}`, import.meta.url).href;
};
export const getVideo = (str: any) => {
  return new URL(`../assets/video/${str}`, import.meta.url).href;
};
export const filterParams = (object: any) => {
  if (isEmptyType(object)) return object;
  const tmpObject: any = {};
  Object.keys(object).forEach((key) => {
    if (!isEmptyType(object[key])) {
      tmpObject[key] = object[key];
    }
  });
  return tmpObject;
};

function isEmpty(val: any) {
  // null or undefined
  if (val == null) return true;
  if (typeof val === "boolean") return false;
  if (typeof val === "number") return !val;
  if (val instanceof Error) return val.message === "";
  switch (Object.prototype.toString.call(val)) {
    // String or Array
    case "[object String]":
    case "[object Array]":
      return !val.length;
    // Map or Set or File
    case "[object File]":
    case "[object Map]":
    case "[object Set]": {
      return !val.size;
    }
    // Plain Object
    case "[object Object]": {
      return !Object.keys(val).length;
    }
  }
  return false;
}
export function buildUrl(url: string, params: any) {
  let queryString = "";
  for (let key in params) {
    if (params.hasOwnProperty(key) && !isEmpty(params[key])) {
      queryString +=
        encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
    }
  }
  queryString = queryString.slice(0, -1);
  return url + "?" + queryString;
}

export function scrollElementTopUp(
  behavior: any = "instant",
  element = document.body
) {
  element.scrollTo({
    left: 0,
    top: 0,
    behavior,
  });
}

export function getHashSearchParam(key: string) {
  let search = /(?<=#.*\?).*/.exec(window.location.href)?.[0];
  let usp = new URLSearchParams(search);
  return usp.get(key);
}
export function getSearchParam(key: string) {
  let string = new URLSearchParams(window.location.search).get(key);
  if (!!string) {
    return string;
  }
  return getHashSearchParam(key);
}
export function removeNewlines(str: string) {
  return str.replace(/[\n\r\t]+/g, "");
}
export function removeSpacesAndNewLines(str: string) {
  // 使用正则表达式匹配所有空格，包括空格、制表符、换行等，并替换为空字符串
  return str.replace(/\s+/g, "");
}
export function getDefineName(path: string) {
  function capitalizeFirstLetter(string: string) {
    return string.toLowerCase().replace(/\b[a-z]/g, function (match: string) {
      return match.toUpperCase();
    });
  }
  return removeSpacesAndNewLines(
    capitalizeFirstLetter(path.replace(/\//g, "")) + "Index"
  );
}

export function loadScript(url: string, callback: () => void) {
  try {
    let script: any = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.setAttribute("crossorigin", "anonymous");

    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = function () {
        callback();
      };
      script.onerror = (event: any) => {
        console.log(event);
      };
    }
    script.src = url;
    document.head.appendChild(script);
  } catch (e) {
    console.error("Error loading script:", e);
  }
}

export function getRandomValue(array = [0, 1, 2, 3, 4, 5, 6, 7]) {
  var randomIndex = Math.floor(Math.random() * array.length);
  return array[randomIndex];
}
